﻿using Microsoft.Extensions.DependencyInjection;
using Modules.BankSpecialAccount.Entitys;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.BankSpecialAccount.Repositories;

/// <summary>
/// 专户累计进账、线上和线下代发金额统计仓储
/// </summary>
[UseDI(ServiceLifetime.Scoped)]
public class BankSpecialAccountStatisticRepository : Repository<BankSpecialAccountStatistic, DefaultDbContext>
{
    public BankSpecialAccountStatisticRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
    {
    }

    /// <summary>
    /// 通过银行专户账号获取统计信息
    /// </summary>
    /// <param name="account"></param>
    /// <returns></returns>
    public BankSpecialAccountStatistic? GetProjectSpecialAccountStatisticByBankAccount(string account)
    {
        return GetProjectSpecialAccountStatistics(account).FirstOrDefault();
        //Sql sql = Sql.Builder;
        //sql.Select("id").From("project_special_account_statistic").Where("bank_account=@0", account);
        //var id = DbContext.FirstOrDefault<int>(sql);
        //return Get(id);
    }

    public IEnumerable<BankSpecialAccountStatistic> GetProjectSpecialAccountStatistics(string account)
    {
        return GetTopEntities(100, PmSoft.Caching.CachingExpirationType.UsualSingleObject, () =>
          {
              int areaVersion = EntityCacheService.GetAreaVersion("BankAccount", account);
              return $"ProjectSpecialAccountStatistics:{account}:{areaVersion}";
          }, () =>
          {
              Sql sql = Sql.Builder;
              sql.Select("id").From("project_special_account_statistic").Where("bank_account=@0", account);
              return sql;
          });
        //Sql sql = Sql.Builder;
        //sql.Select("id").From("project_special_account_statistic").Where("bank_account=@0", account);
        //var id = DbContext.FirstOrDefault<int>(sql);
        //return Get(id);
    }

    public IEnumerable<BankSpecialAccountStatistic> GetProjectSpecialAccountStatistics(IEnumerable<string> accounts)
    {
        List<BankSpecialAccountStatistic> statistics = new List<BankSpecialAccountStatistic>();
        foreach (var item in accounts)
        {
            var account = GetProjectSpecialAccountStatisticByBankAccount(item);
            if (account != null)
            {
                statistics.Add(account);
            }
        }
        return statistics;
    }
}